﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace TankBattle.Models
{
    public class Sprite
    {
        #region Variable

        private bool allSheet;
        private int count;
        private Vector2 current;
        private Vector2 size;
        private Vector2 sheet;
        private int rate;
        private Texture2D texture;

        #endregion 

        #region properties

        public  Vector2 Current
        {
            get { return current; }
            private set { }
        }

        #endregion

        #region Construction

        public Sprite(Texture2D texture, Vector2 size, Vector2 sheet, int rate)
        {
            Initalize(texture, size, sheet, rate, false);
        }
        public Sprite(Texture2D texture, Vector2 size, Vector2 sheet, int rate, bool allSheet)
        {
            Initalize(texture, size, sheet, rate, allSheet);
        }
        #endregion

        #region Function 

        public void SetRate(int rate)
        {
            this.rate = rate;
            count = -1;
        }
        public void SetCurrentFrame(Vector2 current)
        {
            this.current = current;
        }
        public bool Update()
        {
            count++;
            if (count > rate || count == 0)
            {
                count = 0;
                if (current.X >= sheet.X)
                {
                    current.X = 0;
                    if (!allSheet)
                    {
                        return true;// đã kết thúc một lượt sprite
                    }
                    else if (current.Y < sheet.Y)
                    {
                        current.Y++;
                    }
                }
                else
                {
                    current.X++;
                }
            }
            if (current.X >= sheet.X && current.Y >= sheet.Y)
            {
                current.X = current.Y = 0;
                return true;
            }

            return false;
        }
        public void Draw(SpriteBatch spriteBatch, Vector2 position)
        {
            spriteBatch.Draw(texture, position, 
                new Rectangle((int)(current.X * size.X), 
                    (int)(current.Y * size.Y), 
                    (int)size.X,
                    (int)size.Y),
                    Color.White);
        }

        private void Initalize(Texture2D texture, Vector2 size, Vector2 sheet, int rate, bool allSheet)
        {
            this.texture = texture;
            this.size = size;
            this.sheet = sheet;
            this.rate = rate;
            this.current = new Vector2(0, 0);
            this.count = 0;
            this.allSheet = allSheet;
        }

        #endregion 

    }
}
